<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img v-if="avatar" :src="avatar" alt="" />
      <img v-else src="../../../assets/images/avatar.jpg" alt="" />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input type="file" style="display: none" ref="inpt" accept="image/*" @change="changeImg">
        <el-button type="primary" icon="el-icon-plus" @click="$refs.inpt.click()">选择图片</el-button>
        <el-button type="success" icon="el-icon-upload" :disabled="!avatar" @click="hSubmit">上传头像</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data () {
    return {
      avatar: ''
    }
  },
  methods: {
    changeImg (e) {
      const file = e.target.files[0]
      // console.log(file)
      if (file) {
        const fr = new FileReader()
        // 读取文件 获取baseURL64的字符串
        fr.readAsDataURL(file)
        fr.onload = (e) => {
        // console.log(e)
          this.avatar = e.target.result
        // console.log(this.avatar)
        }
      } else {
        this.avatar = ''
      }
    },
    async hSubmit () {
      const { data: res } = await this.$axios.patch('/my/update/avatar', { avatar: this.avatar })
      // console.log(res)
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.$store.dispatch('user/getUserInfo')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
}
</style>
